package com.chris.blog.controller;

import com.chris.blog.entity.po.BlogPO;
import com.chris.blog.entity.po.BlogCategoryPO;
import com.chris.blog.entity.po.CommentPO;
import com.chris.blog.entity.po.UserPO;
import com.chris.blog.service.*;
import com.chris.blog.entity.vo.BlogWriteForm;
import com.alibaba.fastjson.JSONObject;
import com.chris.blog.util.SnowflakeIdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
public class BlogController {

    @Autowired
    BlogService blogService;
    @Autowired
    BlogCategoryService blogCategoryService;
    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;
    @Autowired
    FileUploadService fileUploadService;

    // 编辑一个新的博客 这是展示页
    @GetMapping("/blog/write")
    public String toWrite(Model model) {
        // 查询所有博客的标签 放入
        List<BlogCategoryPO> categoryList = blogCategoryService.selectAll();
        model.addAttribute("categoryList", categoryList);
        return "blog/write";
    }

    /**
     * 博客列表展示请求
     */
    @GetMapping("/blog")
    public String lists(Model model,
                        @RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "10") int limit) {
        // 默认一页显示10条数据 根据更新的时间来定
        PageHelper.startPage(page, limit);
        PageInfo<BlogPO> info = new PageInfo<>(blogService.findAllDesc());
        model.addAttribute("info", info);
        List<BlogCategoryPO> categories = blogCategoryService.selectAll();
        model.addAttribute("categoryList", categories);
        return "blog/list";
    }

    @GetMapping("/blog/read/{bid}")
    public String read(Model model, @PathVariable("bid") Long bid) {
        BlogPO blogPO = blogService.findOneByBid(bid);
        // 每刷新一次 浏览量+1
        blogPO.setViews(blogPO.getViews() + 1);
        blogService.updateByPrimaryKeySelective(blogPO);
        model.addAttribute("blog", blogPO);
        // 评论里的topic_id 对应的就是博客对象里的bid
        List<CommentPO> commentPOS = commentService.selectAllByTopic(bid);
        model.addAttribute("comments", commentPOS);
        return "blog/read";
    }

    /**
     * 保存博客
     *
     * @param blogWriteForm
     * @return
     */
    @PostMapping("/blog/write")
    public String save(BlogWriteForm blogWriteForm) {
        // 接受博客表单vo
        BlogPO blogPO = new BlogPO();
        Long bid = SnowflakeIdWorker.nextId();
        blogPO.setBid(bid);
        blogPO.setTitle(blogWriteForm.getTitle());
        blogPO.setContent(blogWriteForm.getContent());
        blogPO.setSort(0);
        blogPO.setViews(0);
        // 设置用户相关
        blogPO.setAuthorId(blogWriteForm.getAuthorId());
        blogPO.setAuthorAvatar(blogWriteForm.getAuthorAvatar());
        blogPO.setAuthorName(blogWriteForm.getAuthorName());
        // 设置栏目相关
        BlogCategoryPO category = blogCategoryService.selectByPrimaryKey(blogWriteForm.getCategoryId());
        blogPO.setCategoryId(category.getId());
        blogPO.setCategoryName(category.getCategory());
        Date nowDate = new Date();
        blogPO.setGmtCreate(nowDate);
        blogPO.setGmtModified(nowDate);
        blogService.insertSelective(blogPO);

        return "redirect:/blog/read/" + bid;

    }

    /**
     * 更新博客
     *
     * @param blogPO
     * @return
     */
    @PostMapping("/blog/edit")
    public String update(BlogPO blogPO) {
        Long bid = blogPO.getBid();
        BlogPO queryBlogPO = blogService.findOneByBid(bid);
        queryBlogPO.setTitle(blogPO.getTitle());
        queryBlogPO.setContent(blogPO.getContent());
        queryBlogPO.setCategoryId(blogPO.getCategoryId());
        queryBlogPO.setGmtModified(new Date());
        blogService.updateByPrimaryKeySelective(queryBlogPO);
        return "redirect:/blog/read/" + bid;
    }

    /**
     * 删除博客
     */
    @GetMapping("blog/delete/{uid}/{bid}")
    public String delete(@PathVariable("uid") String uid,@PathVariable("bid") Long bid) {
        // 删除两张表的数据 博客表  评论表对应的都要删掉 评论就别删了 太麻烦了
        BlogPO blogPO = blogService.findOneByBid(bid);
        UserPO userPO = userService.findUserByUid(uid);
        if (blogPO.getAuthorId().equals(uid) || userPO.getRoleId() == 1) {
            blogService.deleteByPrimaryKey(blogPO.getId());
            return "redirect:/blog";
        } else {
            return "error/404";
        }

    }
    /**
     * 编辑博客
     */
    @GetMapping("blog/edit/{uid}/{bid}")
    public String edit(Model model,@PathVariable("uid") String uid,@PathVariable("bid") Long bid) {
        // 根据bid 得到blog对象 进行回显 同时标签集合也要传到前端
        // 只有该用户或者管理员可以进行修改
        UserPO userPO = userService.findUserByUid(uid);
        BlogPO blogPO = blogService.findOneByBid(bid);
        if (blogPO.getAuthorId().equals(uid) || userPO.getRoleId() == 1) {
            model.addAttribute("blog", blogPO);
            // 查询所有标签
            List<BlogCategoryPO> categories = blogCategoryService.selectAll();
            model.addAttribute("categoryList", categories);
            return "blog/edit";
        } else {
            return "error/404";
        }
    }

    /**
     *  发表评论
     *
     * @param bid
     * @param commentPO
     * @return
     */
    @PostMapping("/blog/comment/{bid}")
    public String comment(@PathVariable("bid") Long bid, CommentPO commentPO) {
        Long commentId = SnowflakeIdWorker.nextId();
        commentPO.setCommentId(commentId);
        // 1为博客 2为博客
        commentPO.setTopicCategory(2);
        commentPO.setGmtCreate(new Date());
        commentService.insertSelective(commentPO);
        BlogPO blogPO = blogService.findOneByBid(bid);
        // 重定向到博客详情页
        return "redirect:/blog/read/" + bid;
    }


    /**
     * 编辑器图片上传
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/blog/write/file/upload")
    @ResponseBody
    // editormd-image-file不可更改
    public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
        String upload = fileUploadService.upload(file);
        // 给editormd进行回调
        JSONObject res = new JSONObject();
        res.put("url", upload);
        res.put("success", 1);
        res.put("message", "upload success!");
        return res;
    }
}
